package 剑指offer;

public class 矩阵中的路径 {

    public boolean exist(char[][] board, String word) {
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                if (board[i][j]!=word.charAt(0))
                    continue;
                if (bfs(board,word,i,j,0))
                return true;
            }
        }
        return false;
    }

    private boolean bfs(char[][] board, String word, int i, int j,int num) {
         if (num==word.length()-1)
             return true;
//         边界条件
        if (i<0 || i>=board.length || j<0 || j>=board[0].length || word.charAt(num)!=board[i][j])
            return false;
        char c = board[i][j];
        board[i][j]=' ';
        //向上 向下 向左 向右
        boolean res = bfs(board,word,i+1,j,num+1) || bfs(board,word,i-1,j,num+1)
        ||  bfs(board,word,i,j-1,num+1) || bfs(board,word,i,j+1,num+1);
        board[i][j]=c;
        return res;
    }
}
